package com.yeban.bams.entity;

import com.yeban.bams.exception.LoanException;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/13
 *
 * 2 - 可贷款储蓄账户
 * 可以贷款,不可以透支
 */
public class LoanableSavingsAccount extends SavingAccount implements Loanable{

    private long loanAmount;    // 记录贷款金额
    private static final long serialVersionUID = -4904727076730297531L;

    public LoanableSavingsAccount() {
    }

    public LoanableSavingsAccount(Long id, String password, String name, String personId, String email, double balance, long loanAmount) {
        super(id, password, name, personId, email, balance);
        this.loanAmount = loanAmount;
        this.setType(2);
    }

    /**
     * 贷款
     * @param money 贷款金额
     * @return
     */
    @Override
    public Account requestLoan(double money) throws LoanException {
        // 贷款金额money < 0
        if(money < 0.0) {
            throw new LoanException("贷款金额必须为正数！");
        }
        // 贷款
        loanAmount += money;                            // 设置贷款额
        this.setBalance(this.getBalance() + money);     // 贷款的钱到账户上
        return this;
    }

    /**
     * 还款
     * @param money 还款金额
     * @return
     */
    @Override
    public Account payLoan(double money) throws LoanException {
        // 还款金额money < 0
        if(money < 0.0) {
            throw new LoanException("还款金额必须为正数！");
        }

        // 还款金额money > 贷款额loanAmount
        if(money > loanAmount) {
            throw new LoanException("还款金额超出贷款额！");
        }

        //  还款逻辑
        double balance = getBalance();
        if(money <= balance) {   // 还款金额money <= 余额balance
            setBalance(balance - money);
            loanAmount -= money;
        } else {                    // 还款金额money > 余额balance
            throw new LoanException("还款失败！您的账户余额不足！");
        }
        return this;
    }

    /**
     * 获取
     * @return loanAmount
     */
    public long getLoanAmount() {
        return loanAmount;
    }

    /**
     * 设置
     * @param loanAmount
     */
    public void setLoanAmount(long loanAmount) {
        this.loanAmount = loanAmount;
    }

    @Override
    public String toString() {
        return "LoanableSavingsAccount{" +
                "loanAmount=" + loanAmount +
                '}' + super.toString();
    }
}
